package top.ranzhang.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.util.DigestUtils;
import top.ranzhang.bean.dto.AdminLoginDTO;
import top.ranzhang.bean.dto.EmailOtherDTO;
import top.ranzhang.bean.entity.Admin;
import top.ranzhang.common.properties.JwtProperties;
import top.ranzhang.constant.JwtClaimsConstant;
import top.ranzhang.exception.BaseException;
import top.ranzhang.mapper.AdminMapper;
import top.ranzhang.mapper.OtherMapper;
import top.ranzhang.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import top.ranzhang.bean.vo.AdminVO;
import top.ranzhang.utils.JwtUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ran
 * @since 2025-04-14
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    private final JwtProperties jwtProperties;

    private final JavaMailSender javaMailSender;

    private final RedisTemplate redisTemplate;

    private final OtherMapper otherMapper;

    @Override
    public AdminVO login(AdminLoginDTO adminLoginDTO) {
        //采用mybatis-plus的查询方式，方便查询不要去操作mapper层
        // 根据用户名查询用户
        Admin admin = lambdaQuery()
                //ge等于sql=
                //括号里面的前面是数据库对字段名，括号里面的后面是值
                .ge(Admin::getUsername, adminLoginDTO.getUsername())
                // 查询结果放回一条
                .one();
        if(admin == null){
            throw new BaseException("用户不存在");
        }
        //为了保存数据被人偷取，这边进行密码加密
        if(!admin.getPassword().equals(DigestUtils.md5DigestAsHex(adminLoginDTO.getPassword().getBytes()))){
            throw new BaseException("密码错误");
        }
        // 生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.Employee_ID, admin.getId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        //应为AdminVO类加了@Builder注解，所以可以这样写,快速生成对象
        return AdminVO.builder()
                .id(admin.getId())
                .username(admin.getUsername())
                .token(token)
                .password("***")
                .build();
     }

    @Override
    public String getEmailCode() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++){
            code  += random.nextInt(10);
        }
        return code;
    }


}
